SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SaveLogItem]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SaveLogItem]
GO


/***************************************************************************
* Name:			SaveLogItem
* Purpose:		Save /Update LogItem
*
* PARAMETERS
* Name				Description					
* -------------		-----------------------------------------------------------
* @id				Log item Id for updation
* @questionnaireVersionId	Questionnaire Version Id corresponding to LogItem
* @type				LogItem Type
* @category			Category
* @questionName			Question name
* @answer			Answer
* @completed			Check Flag status of the Log Item


***************************************************************************/

CREATE PROCEDURE SaveLogItem(
@id			INTEGER,
@questionnaireVersionId	INTEGER,
@questionnaireAnswerId	INTEGER,
@type			VARCHAR(256),
@category		VARCHAR(256),
@questionName		VARCHAR(256),
@answer			VARCHAR(256),
@description		VARCHAR(256),
@completed		BIT
)
AS 

BEGIN

	SET NOCOUNT ON


	IF @id=0

		BEGIN
			INSERT INTO LOGITEM (	questionnaireVersionId,
					questionnaireAnswerId,
					Type,
					Category,
					QuestionName,
					Answer,
					Description,
					Completed  ) 
				VALUES
				    (	@questionnaireVersionId,
					@questionnaireAnswerId,	
					@type,
					@category,
					@questionName,
					@answer,
					@description,
					@completed )
				
			IF @@ERROR <> 0 GOTO ERROR_HANDLER

			SELECT @id = IDENT_CURRENT('LogItem')	

			SELECT @id

			RETURN
		END		
	ELSE
		BEGIN

			UPDATE LogItem SET 	
			QuestionnaireVersionId = @questionnaireVersionId,
			QuestionnaireAnswerId = @questionnaireAnswerId,
			Type = @Type,
			Category = @category,
			QuestionName = @questionName,
			Answer = @answer,
			Description = @description,
			Completed = @completed
			WHERE [Id] = @id

			IF @@ERROR <> 0 GOTO ERROR_HANDLER

			SELECT @id	
			RETURN

		END


	ERROR_HANDLER:
		IF @@ERROR <> 0 
		BEGIN
			RAISERROR('Unable to save LogItem ', 16, 1)
			RETURN
		END
END
